package com.marver.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.marver.common.result.Result;
import com.marver.common.result.ResultStatus;
import com.marver.beans.UserQo;
import com.marver.common.utils.HttpUtil;
import com.marver.common.utils.ValidDataUtil;
import com.marver.common.utils.group.QueryGroup;
import com.marver.entity.qo.Param;
import com.marver.shiro.ShiroUtils;
import com.marver.sys.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @description: 用户登录相关
 * @Author: Marver
 * @date: 2018-04-26 15:34
 **/
@Controller
@RequestMapping("userLogin")
public class UserLoginController {
    @Autowired
    private Producer producer;
    @Autowired
    private UserService userService;

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @PostMapping(value = "/login")
    public Result login(HttpServletRequest request, @RequestBody Param<UserQo> param) {
        ValidDataUtil.validateEntity(param.getBody(), QueryGroup.class);
        UserQo qo = param.getBody();

        Object kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(kaptcha==null){
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),"验证码已失效!");
        }
        if(!qo.getCaptcha().equalsIgnoreCase(kaptcha.toString())){
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),"验证码不正确");
        }

        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(qo.getMobile(), qo.getPassword());
            subject.login(token);
        }catch (UnknownAccountException e) {
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),"账号或密码不正确");
        }catch (LockedAccountException e) {
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),"账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return new Result(ResultStatus.FAIL.getErrorCodeToString(),"账户验证失败");
        }
        List<Map> list = userService.createToken(HttpUtil.getClientIP(request));
        return new Result(ResultStatus.SUCCESS.getErrorCode(),list);
    }

    /**
     * 退出
     */
    @ResponseBody
    @RequestMapping(value = "logout" , method = RequestMethod.GET)
    public Result logout(){
        ShiroUtils.logout();
        return new Result(ResultStatus.SUCCESS.getErrorCodeToString(),"SUCCESS");
    }
}
